const { app, BrowserWindow, ipcMain } = require("electron");
const isDev = require("electron-is-dev");
const glob = require("glob");
const path = require("path");
const logger = require("./main-process/modules/logger.js");
const sqlite3 = require("sqlite3");
const fs = require("fs");
let db = new sqlite3.Database("electron-quick-start-db.db");
const http = require("http");
const {
  unzip,
  time_string,
  deleteFolder,
  moveFile,
  dirPath,
} = require("./uitls.js");
const { pinyin } = require("pinyin-pro");

// 查询 用户名和密码是否相同
/**
 *
 */
function createWindow() {
  const win = new BrowserWindow({
    width: 1000,
    height: 800,
    backgroundColor: "#2e2c29",
    webPreferences: {
      nodeIntegration: true,
      preload: path.join(__dirname, "preload.js"),
    },
  });

  const localFile = `file://${path.join(__dirname, "../build/index.html")}`;
  win.loadURL(isDev ? "http://localhost:3000" : localFile);
  haveTableData();
  haveTableFile();
  server.listen(8989, () => {
    console.log("Server is running on http://localhost:8989");
  });
}

logger.info(
  `app start path[file://${path.join(__dirname, "../build/index.html")}]`
);

// Quit when all windows are closed.
app.on("window-all-closed", () => {
  // 在 macOS 上，除非用户用 Cmd + Q 确定地退出，
  // 否则绝大部分应用及其菜单栏会保持激活。
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("activate", () => {
  // 在macOS上，当单击dock图标并且没有其他窗口打开时，
  // 通常在应用程序中重新创建一个窗口。
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

//拆分 用require 导入。
function loadApp() {
  const files = glob.sync(path.join(__dirname, "main-process/app/**/*.js"));
  files.forEach((file) => {
    require(file);
  });
}

loadApp();

//----------------------------------查询数据库方法--------------------------------

const createTableSql = `
CREATE TABLE standard_terminology (
    term_name                 TEXT,
    term_ename                TEXT,
    standard_name             TEXT,
    standard_no               TEXT,
    term_name_page            TEXT,
    standard_name_pinyin      Text,
    term_name_pinyin          TEXT,
    remark                    TEXT,
    id                        TEXT
);`;
const createTableFile = `
CREATE TABLE file_list (
    standard_no      TEXT,
    file_base_path   TEXT
);
`;

const haveTableData = () => {
  db.all(
    "SELECT name FROM sqlite_master WHERE type='table' AND name='standard_terminology';",
    (err, row) => {
      if (row[0]?.name === "standard_terminology") {
      } else {
        // 表不存在
        db.all(createTableSql);
        return false;
      }
    }
  );
};

const haveTableFile = () => {
  return db.all(
    "SELECT name FROM sqlite_master WHERE type='table' AND name='file_list';",
    (err, row) => {
      if (row[0]?.name === "file_list") {
      } else {
        // 表不存在
        db.all(createTableFile);
      }
    }
  );
};

InsetJsonData = async (event, data) => {
  db.serialize(() => {
    db.run("BEGIN TRANSACTION"); // 开始事务
    for (let i = 0; i < data.length; i++) {
      const term_name = data[i]["termName"];
      const term_ename = data[i]["termEname"];
      const term_name_pinyin = pinyin(data[i]["termName"], {
        toneType: "none",
      });
      const standard_name = data[i]["standardName"];
      const standard_no = data[i]["standardNo"];
      const standard_name_pinyin = pinyin(data[i]["standardName"], {
        toneType: "none",
      });
      const id = `${i}_term_name`;
      const term_name_page = data[i]["page"];
      db.run(
        `INSERT INTO standard_terminology (term_name, term_ename, term_name_pinyin, standard_name, standard_no,term_name_page,standard_name_pinyin,id) VALUES (?, ?, ?, ?, ?, ? ,? ,?)`,
        [
          term_name,
          term_ename,
          term_name_pinyin,
          standard_name,
          standard_no,
          term_name_page,
          standard_name_pinyin,
          id,
        ]
      );
    }
    db.run("COMMIT TRANSACTION"); // 提交事务
  });
};

// 模糊查询数据
const serchLike = async (event, serchObj) => {
  const { keys, values } = serchObj;
  const SQL = `SELECT * FROM standard_terminology  WHERE ${keys} LIKE '%${values}%';`;

  // return db.all(SQL);
  return universalProcessing(SQL);
};

// 按照条件查询数据列表
const getDataList = async (evevt, option) => {
  const {
    term_name = null,
    term_ename = null,
    standard_name = null,
    standard_no = null,
    page = 1,
    pageSize = 10,
  } = option;
  const offset = (page - 1) * pageSize;

  let SQL = `SELECT *
  FROM standard_terminology
  WHERE
      (CASE WHEN ${
        term_name ? `'${term_name}'` : null
      } IS NOT NULL THEN term_name LIKE '%${term_name}%' ELSE 1=1 END) AND
      (CASE WHEN ${
        term_ename ? `'${term_ename}'` : null
      } IS NOT NULL THEN term_ename LIKE '%${term_ename}%' ELSE 1=1 END) AND
      (CASE WHEN ${
        standard_name ? `'${standard_name}'` : null
      } IS NOT NULL THEN standard_name LIKE '%${standard_name}%' ELSE 1=1 END) AND
      (CASE WHEN ${
        standard_no ? `'${standard_no}'` : null
      } IS NOT NULL THEN standard_no LIKE '%${standard_no}%' ELSE 1=1 END) LIMIT ${pageSize} OFFSET ${offset};`;

  return universalProcessing(SQL);
};

const findListTotle = async () => {
  const SQL = `SELECT COUNT(*) AS total FROM standard_terminology`;
  return universalProcessing(SQL);
};
// 保存pdf文件
const savePdfBase64 = async (event, fileData) => {
  const { standard_no, filePath } = fileData;
  let new_standard_no = standard_no.replace(/[^a-zA-Z0-9_]/g, "_");

  // 将缓冲区数据写入文件
  db.serialize(() => {
    db.run("BEGIN TRANSACTION"); // 开始事务
    db.run(
      `INSERT INTO file_list (standard_no, file_base_path) VALUES (?, ?)`,
      [new_standard_no, filePath]
    );
    db.run("COMMIT TRANSACTION", (err) => {
      console.log(err);
    }); // 提交事务
  });
};

const findPdf = async (event, data) => {
  const { standard_no } = data;
  const new_no = standard_no.replace(/[^a-zA-Z0-9_]/g, "_");

  const SQL = `SELECT * FROM file_list WHERE standard_no = '${new_no}';`;
  universalProcessing(SQL).then((result) => {});
};

const setRemark = (event, data) => {
  const { id, remark } = data;

  const SQL = `UPDATE standard_terminology SET remark = '${remark}' WHERE id = '${id}' `;

  return universalProcessing(SQL);
};

const universalProcessing = (findUserSql) => {
  return new Promise((reslove, project) => {
    db.all(findUserSql, (err, rows) => {
      if (err) {
        // alert(err.message);
        // project(err);
      } else {
        reslove(rows);
      }
    });
  });
};

// ++++++=++++++++++++++++++++++++++++++++++++++++++++++++++++++++=服务器代码========================

const server = http.createServer((req, res) => {
  // 假设请求的是 /file 路径
  res.setHeader("Access-Control-Allow-Origin", "*"); // 允许任何源
  res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); // 允许的方法
  res.setHeader("Access-Control-Allow-Headers", "Content-Type"); // 允许的头部
  // 设置流的格式为二进制
  if (req.url.includes("file")) {
    const standard_no = decodeURIComponent(req.url.split("=")[1]).replace(
      /[^a-zA-Z0-9_]/g,
      "_"
    );
    const SQL = `SELECT * FROM file_list WHERE standard_no = '${standard_no}';`;
    universalProcessing(SQL).then((result) => {
      const filePath = result[0]["file_base_path"];
      console.log(result);
      fs.readFile(filePath, (err, data) => {
        if (err) {
          res.writeHead(500);
          return res.end("Server Error");
        }
        res.setHeader("Content-Type", "application/pdf");
        res.setHeader(
          "Content-Disposition",
          `inline; filename='${standard_no}.pdf`
        );
        res.writeHead(200);
        res.end(data);
      });
    });
  } else if (req.url.includes("/upload") && req.method === "POST") {
    fs.mkdir(".", () => {
      const writeStream = fs.createWriteStream(`./${req.url}`);
      req.pipe(writeStream);
      writeStream.on("finish", () => {
        upLoadFileForZip(`${req.url}`, `${req.url}`, res);
      });
    });
  } else {
    res.writeHead(404, { "Content-Type": "text/plain" });
    res.end("Not found");
  }

  // 读取文件并以流的形式发送
});

const upLoadFileForZip = async (filePath, uploadMri, res) => {
  const password = "cesi1234"; // 替换为你的密码
  const pathForFile = path.join(dirPath, filePath);
  try {
    await unzip(pathForFile, password, res).then((outPath) => {
      let pdfAndTermJson = [];
      fs.readFile(`${outPath}/jgh_pdf_term.json`, "utf8", (err, data) => {
        try {
          const tremList = JSON.parse(data);
          fs.readFile(`${outPath}/jgh_pdf.json`, "utf8", (err, dataPdf) => {
            try {
              const objPdf = JSON.parse(dataPdf);
              pdfAndTermJson = tremList.reduce((acc, cur) => {
                const { termName, termEname, page, standardNo, pdfId } = cur;
                const pdfObj = objPdf.find((x) => x.id === pdfId);
                let obj = {
                  termName,
                  termEname,
                  page,
                  standardNo,
                  standardName: pdfObj.cname,
                };
                acc.push(obj);
                return acc;
              }, []);
              // 保存术语信息
              InsetJsonData(null, pdfAndTermJson);
              // 保存PDF信息
              for (let i = 0; i < objPdf.length; i++) {
                try {
                  let pdf = objPdf[i];
                  const timeString = pdf.crtTime;
                  const stff = time_string(timeString);
                  const pdfRealName = `${pdf.name.split(".")[0]}_${stff}`;
                  const pointPdfPath = "./pdf/";
                  const pathPdf = `${outPath}/pdf/${pdfRealName}.pdf`;
                  savePdfBase64(null, {
                    standard_no: pdf.standardNo.replace(/[^a-zA-Z0-9_]/g, "_"),
                    filePath: path.join(`./pdf/${pdfRealName}.pdf`),
                  });
                  fs.unlinkSync(`./${uploadMri}`);
                  let timeInvel = setInterval(() => {
                    if (fs.existsSync(outPath)) {
                      moveFile(pathPdf, pointPdfPath, `${pdfRealName}.pdf`);
                      setTimeout(() => {
                        deleteFolder(outPath);
                        clearInterval(timeInvel);
                        const response = { statusFile: "true" };
                        res.end(JSON.stringify(response));
                      }, 10000);
                    } else {
                      console.error(`${outPath} does not exist.`);
                    }
                  }, 3000);
                } catch (e) {
                  const response = { message: e };
                  res.end(JSON.stringify(response));
                  console.log(e);
                }
              }
            } catch (e) {
              const response = { message: e };
              res.end(JSON.stringify(response));
            }
          });
        } catch (e) {
          const response = { message: "" };
          res.end(JSON.stringify(response));
        }
      });
    });
  } catch (e) {
    console.log(e);
  }
};

app.whenReady().then(() => {
  ipcMain.handle("set-json", InsetJsonData);
  ipcMain.handle("set-option", serchLike);
  ipcMain.handle("get-list", getDataList);
  ipcMain.handle("set-pdf", savePdfBase64);
  ipcMain.handle("find-pdf", findPdf);
  ipcMain.handle("get-totl", findListTotle);
  ipcMain.handle("set-remark", setRemark);
  createWindow();
});

// 生成快捷方式
if (require("electron-squirrel-startup")) return;
